/**
 * Created by maple on 2016/6/9.
 */
var request = require('request');
//使用$字符，因为在web上，jquery符号就是，更好的看着统一而已
var cheerio = require("cheerio");


var indexUrl = "http://www.51sfzd.com/CharCollectionSystem/index.php/Report/index";
var reportUrl = "http://www.51sfzd.com/CharCollectionSystem/index.php/Report/report";

//通过第一次请求获取HashCode
function getHashCodeAndCookie(callback) {
    request(indexUrl, function (error, res, body) {
        if (!error && res.statusCode == 200) {
            //获取页面验证的Hash
            var $ = cheerio.load(body);
            var info = $('input[name="__hash__"][type="hidden"]').val();
            //获取cookie
            var cookie = res.headers['set-cookie'];
            callback(info, cookie);
        }
    });
}

function reportChar(strinfo,callback) {

    getHashCodeAndCookie(function (hashCode, cookie) {
        //获取到HashCode然后进行解析
        request({
            url: reportUrl,
            method: 'POST',
            headers:{
                ContentType:'application/x-www-form-urlencoded',
                Cookie:cookie,
            },
            form: {
                strs: strinfo,
                start_check: '%E5%BC%80%E5%A7%8B%E6%A3%80%E6%B5%8B',
                __hash__: hashCode
            }

        }, function (err, response, body) {
            //获取返回结果网页，并且进行相应的解析
            //获取页面验证的Hash
            var $ = cheerio.load(body);
            var info = $.html('div[class="right"]');
            var result = {
                status : 1,
                data:info,
                info:''
            };
            callback(result);
        });
    });
}


module.exports = reportChar;